package cn.clx.ymcc.listener;

import cn.clx.ymcc.domain.CourseOrder;
import cn.clx.ymcc.domain.CourseOrderItem;
import cn.clx.ymcc.dto.PayDto;
import cn.clx.ymcc.service.ICourseOrderItemService;
import cn.clx.ymcc.service.ICourseOrderService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 事务监听
 */
@Component
@Slf4j
@RocketMQTransactionListener(txProducerGroup="service-order-course-pay-producer")
public class CourseOrderListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Autowired
    private ICourseOrderItemService courseOrderItemService;

    /**
     * 执行本地事务
     * @param message
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        log.info("开始执行本地事务");
        try {
            CourseOrder order = (CourseOrder) arg;
            courseOrderService.insert(order);
            List<CourseOrderItem> courseOrderItems = order.getCourseOrderItems();
            for (CourseOrderItem courseOrderItem : courseOrderItems) {
                courseOrderItem.setOrderId(order.getId());
                courseOrderItemService.insert(courseOrderItem);
            }
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }

    /**
     * 回查本地事务是否成功
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] payload =(byte[]) message.getPayload();
            String paydto = new String(payload, StandardCharsets.UTF_8);
            PayDto payDto = JSON.parseObject(paydto, PayDto.class);
            String orderNo = payDto.getOrderNo();
            CourseOrder order =courseOrderService.findOrderByOrderNo(orderNo);
            return order==null?RocketMQLocalTransactionState.ROLLBACK:RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
